package common.library.activities;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import common.library.R;
import common.library.models.StringCallback;
import common.library.utils.ApplicationUtil;
import common.library.utils.ViewUtil;
import lombok.var;

//declared activity in AndroidManifest.xml
public class SelectFolderActivity extends AppCompatActivity {

    EditText editText;
    ArrayList<String> listItems;

    void InitList(String path) {
        editText.setText(path);

        File[] files;
        if (path.equals("/"))
            files = File.listRoots();
        else
            files = new File(path).listFiles();

        listItems.clear();
        for (File file : files) {
            if (file.isDirectory()) {
                listItems.add(file.getAbsolutePath());
            }
        }
    }

    void createFolder(String path) {
        var newPath = path;
        if (path.equals("/"))
            newPath = File.listRoots()[0].getPath();
        newPath += "new folder";
        new File(newPath).mkdir();
        InitList(path);
    }

    public static StringCallback callback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_folder);

        editText = findViewById(R.id.editText);
        ListView listView = findViewById(R.id.listView);

        listItems = new ArrayList();
        listView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, listItems));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                var textView = (AppCompatTextView) view;
                InitList(textView.getText().toString());
            }
        });

        ViewUtil.addClickListener(this, R.id.buttonCreate, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createFolder(editText.getText().toString());
            }
        });

        ViewUtil.addClickListener(this, R.id.buttonSelect, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.run(editText.getText().toString());
                finish();
            }
        });

        InitList("/");
    }
}